package com.hmall.item.web;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.apache.ibatis.annotations.Update;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.RabbitRetryTemplateCustomizer;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/item")
public class ItemController {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    private IItemService itemService;

    @GetMapping("/list")
    public PageDTO<List<Item>> list(@RequestParam(value = "page",defaultValue = "1")Integer page,
                                   @RequestParam(value = "size",defaultValue = "5")Integer size){
        IPage<Item> page1=new Page<>(page,size);
        IPage<Item>pageInfo=itemService.page(page1,null);
        PageDTO pageDTO=new PageDTO();
        Long total=pageInfo.getTotal();
        List<Item> records=pageInfo.getRecords();
        pageDTO.setTotal(total);
        pageDTO.setList(records);
        return pageDTO;

    }
    @GetMapping("/{id}")
    public Item ListById(@PathVariable("id") Long id){
        Item item = itemService.getById(id);
        return item;
    }

    /**
     * 添加商品
     * @param item
     */
    @PostMapping()
    public void insert(@RequestBody Item item){
        Item item1=new Item();
        item1.setCreateTime(new Date());
        System.out.println(item1);
        itemService.save(item);
        //发信息到rabbitMQ
        rabbitTemplate.convertAndSend("item.direct","item.update", JSON.toJSONString(item));
        System.err.println("已发送信息成功");
    }
    @PutMapping("/status/{id}/{status}")
    public void xiajia(@PathVariable("id") Long id,
                       @PathVariable("status") Integer status){
        itemService.xiajia(id,status);
    }
    @PutMapping()
    public void update(@RequestBody Item item){
        item.setUpdateTime(new Date());
        itemService.updateById(item);
        //发信息到  MQ
        rabbitTemplate.convertAndSend("item.direct","item.update",JSON.toJSONString(item));
        System.err.println("已发送信息成功");
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable("id") Long id){
        itemService.removeById(id);
        //发信息到  MQ
        rabbitTemplate.convertAndSend("item.direct","item.delete",id.toString());
        System.err.println("已发送信息成功");

    }
}
